package com.mystudy.concurrent.designModel.readWiriteModel;

/**
 * TODO: 共享数据
 *
 * @author acy
 * @since 2019/05/28 20:23
 */
public class SharedData {
	private final char[] buffer;

	private final MyReadWriteLock lock = new MyReadWriteLock();

	public SharedData(int size) {
		this.buffer = new char[size];
		for (int i = 0; i < size; i++) {
			buffer[i] = '*';
		}
	}

	public char[] read() {
		try {
			lock.readLock();
			return doRead();
		}finally {
			lock.readUnlock();
		}
	}

	private char[] doRead() {
		char[] newBuf=new char[buffer.length];
		for (int i = 0; i < newBuf.length; i++) {
			newBuf[i]=buffer[i];
		}
		slowly(50);
		return new char[0];
	}

	private void slowly(int ms){
		try {
			Thread.sleep(ms);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void write(char c){
		for (int i = 0; i < buffer.length; i++) {
			buffer[i]=c;
			slowly(50);
		}
	}
}
